import 'package:management/model/visitor_model.dart';
import 'package:sqflite/sqflite.dart';

final String tableDepartment = "department";
final String columnDepartmentName = "name";

///部门模型
class Department {
  ///部门名称
  String? name;

  bool? selected;

  Department(this.name, {this.selected = false});

  Department.formMap(Map<String, Object?> map) {
    name = map[columnDepartmentName] as String?;
    selected = false;
  }

  Map<String, Object?> toMap() {
    var map = {columnDepartmentName: name};

    return map;
  }
}

class DepartmentProvider {
  Database? db;

  Future open() async {
    db = await openDatabase(dbPath!);
  }

  Future close() async => db?.close();
  static final DepartmentProvider _departmentProvider =
      DepartmentProvider._internal();

  DepartmentProvider._internal();

  factory DepartmentProvider() {
    return _departmentProvider;
  }

  insert(Department department) async {
    await open();
    await db?.insert(tableDepartment, department.toMap());
    await close();
  }

  Future<int> delete(Department department) async {
    return await db!.delete(tableDepartment,
        where: " $columnDepartmentName = ?", whereArgs: [department.name]);
  }

  Future<List<Department>?> queryAll() async {
    await open();
    List<Map<String, Object?>> maps =
        await db!.query(tableDepartment, columns: [columnDepartmentName]);

    if (maps.length > 0) {
      List<Department> allDepartments = [];
      maps.forEach((element) {
        allDepartments.add(Department.formMap(element));
      });
      await close();
      return allDepartments;
    }
    await close();
    return null;
  }
}
